<template>
    <div id="root">
        <mu-flex justify-content="center" align-items="center">
            <h1 class="title">PHR个人健康服务管理</h1>
        </mu-flex>

        <mu-text-field
                v-model="phoneNumber"
                label="手机号"
                prefix="+86"
                label-float
                full-width
                max-length="11"
                color="primary"
                @change="onPhoneNumberChange"
                :error-text="phoneErrorText"/>

        <mu-slide-left-transition @after-leave="onPasswordAfterLeave">
            <mu-text-field
                    v-model="password"
                    label="密码"
                    label-float
                    full-width
                    color="primary"
                    :error-text="passwordErrorText"
                    :action-icon="visibility ? 'visibility_off' : 'visibility'"
                    :action-click="function() { visibility = !visibility }"
                    :type="visibility ? 'text' : 'password'"
                    @change="onPasswordChange"
                    v-if="usePassword"/>
        </mu-slide-left-transition>

        <mu-slide-right-transition @after-leave="onCodeAfterLeave">
            <mu-flex
                    justify-content="center"
                    align-items="center"
                    v-if="useCode">
                <mu-flex fill>
                    <mu-text-field
                            v-model="code"
                            label="验证码"
                            label-float
                            full-width
                            max-length="6"
                            color="primary"
                            :error-text="codeErrorText"/>
                </mu-flex>
                <mu-button id="btnCode" flat color="primary" @click="onGetCodeBtClick"
                           :disabled="isGettingCode">{{ btnGetCode }}
                </mu-button>
            </mu-flex>
        </mu-slide-right-transition>

        <mu-flex fill justify-content="center">
            <mu-button
                    round
                    full-width
                    color="primary"
                    @click="onLoginClick">登录
            </mu-button>
        </mu-flex>

        <mu-flex fill justify-content="center">
            <mu-button
                    id="btnRegister"
                    flat
                    color="secondary"
                    @click="onRegisterClick">注册
            </mu-button>
        </mu-flex>

        <mu-flex fill justify-content="center">
            <mu-button
                    id="btnLoginMode"
                    flat
                    @click="onLoginModeClick">{{ btnLoginMode }}
            </mu-button>
        </mu-flex>
    </div>
</template>

<script lang="ts">
    import authService from "../../service/auth/AuthService";
    import {SUCCESS} from "../../common/ErrorCode";

    export default {
        data() {
            return {
                phoneNumber: "",
                phoneErrorText: "",
                code: "",
                codeErrorText: "",
                btnGetCode: "获取验证码",
                isGettingCode: false,
                password: "",
                passwordErrorText: "",
                visibility: false,
                usePassword: true,
                useCode: false,
                btnLoginMode: "使用短信验证码登陆",
            }
        },
        methods: {
            onPhoneNumberChange: function (newValue) {
                if (newValue.length < 11) {
                    this.phoneErrorText = "请输入11位的手机号码";
                }
                else {
                    this.phoneErrorText = "";
                }
            },
            onGetCodeBtClick: async function () {
                if (this.phoneNumber.length === 0 || this.phoneErrorText.length > 0) {
                    this.onPhoneNumberChange(this.phoneNumber);
                    return;
                }
                if (this.isGettingCode) {
                    return;
                }
                this.isGettingCode = true;
                let t = 60;
                this.btnGetCode = `${t}s`;
                let id = setInterval(() => {
                    t -= 1;
                    this.btnGetCode = `${t}s`;
                }, 1000);
                setTimeout(() => {
                    clearInterval(id);
                    this.isGettingCode = false;
                    this.btnGetCode = "获取验证码";
                }, t * 1000);

                authService.getMessageCode(this.phoneNumber)
                    .then(result => {
                        if (result.code !== SUCCESS) {
                            this.$toast.info(result.message);
                        }
                    })
                    .catch(() => {
                        this.$toast.info("网络异常");
                    });
            },
            onPasswordChange: function (newValue) {
                if (newValue.length < 6) {
                    this.passwordErrorText = "密码至少6位";
                } else if (!/[a-zA-Z0-9]{6,}/.test(newValue)) {
                    this.passwordErrorText = "密码只支持大小写字母和数字";
                } else {
                    this.passwordErrorText = "";
                }
            },
            onLoginClick: function () {
                if (this.phoneNumber.length === 0 || this.phoneErrorText.length > 0) {
                    this.onPhoneNumberChange(this.phoneNumber);
                } else {
                    if (this.usePassword) {
                        authService.loginWithPassword(this.phoneNumber, this.password)
                            //登录之后会判断targetPath有无信息，如果有就跳转到targetPath界面，否则跳转到home
                            .then(result => {
                                if (result.code === SUCCESS) {
                                    let path = this.$store.state.targetPath;
                                    this.$router.push({name: 'Homepage'});
                                    if(path != null) {
                                        this.$router.push({path: path});
                                        this.$store.commit("resetTargetPath");
                                    }
                                } else {
                                    this.$toast.info(result.message);
                                }
                            })
                            .catch((e) => {
                                console.log(e);
                                this.$toast.info("网络异常");
                            })
                    } else if (this.useCode) {
                        authService.loginWithMessageCode(this.phoneNumber, this.code)
                            .then(result => {
                                if (result.code === SUCCESS) {
                                    let path = this.$store.state.targetPath;
                                    this.$router.push({name: 'Homepage'});
                                    if(path!=null){
                                        console.log(path);
                                        this.$router.push({path: path});
                                        this.$store.commit("resetTargetPath");
                                    }
                                } else {
                                    this.$toast.info(result.message);
                                }
                            })
                            .catch(() => {
                                this.$toast.info("网络异常");
                            })
                    }
                }
            },
            onRegisterClick: function () {
                this.$router.push({name: "Register"});
            },
            onLoginModeClick: function () {
                if (this.usePassword) {
                    this.usePassword = false;
                    this.btnLoginMode = "使用密码登陆";
                } else {
                    this.useCode = false;
                    this.btnLoginMode = "使用短信验证码登陆";
                }
                // console.log(`click: ${this.usePassword} - ${this.useCode}`);
            },
            onPasswordAfterLeave: function () {
                this.useCode = true;
                // console.log(`passwordLeave: ${this.usePassword} - ${this.useCode}`);
            },
            onCodeAfterLeave: function () {
                this.usePassword = true;
                // console.log(`codeLeave: ${this.usePassword} - ${this.useCode}`);
            },
        }
    }
</script>
<style scoped>
    #root {
        position: absolute;
        width: 100%;
        padding: 0 5%;
        top: 40%;
        transform: translateY(-50%);
    }

    .title {
        font-size: 1.5em;
        font-weight: 500;
    }

    #btnCode {
        text-transform: none;
        font-size: 1rem;
        background: rgba(153, 153, 153, .2);
        margin-left: 8px;
    }

    #btnRegister {
        margin-top: 16px;
    }

    #btnLoginMode {
        margin-top: 16px;
    }
</style>